<template>
  <div style="width: 800px; margin: 0 auto">
    <h1>登录页面</h1>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="账号" prop="userName">
        <el-input v-model="ruleForm.userName" placeholder="请输入用户名/邮箱" />
      </el-form-item>
      <el-form-item label="密码" prop="userPass">
        <el-input v-model="ruleForm.userPass" placeholder="请输入密码" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { login } from "@/api/api";
import { useRouter } from "vue-router";

const router = useRouter();
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  userName: "",
  userPass: "",
});

//参数校验
const rules = reactive<FormRules>({
  userName: [{ required: true, message: "请输入账号", trigger: "blur" }],
  userPass: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

//提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      login(ruleForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("登录成功");
          let user = res.data.data;
          let token = user.token;

          //存入session
          sessionStorage.setItem("user", JSON.stringify(user));
          sessionStorage.setItem("token", token);

          //跳转
          router.push("/home");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//取消
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style scoped></style>
